package com.faith.timefloating;

import java.io.IOException;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.ClipboardManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.basv.gifmoviewview.widget.GifMovieView;
import com.faith.timefloating.db.DataBaseHelper;
import com.faith.timefloating.listener.OnMyButtonEvents;
import com.faith.timefloating.model.Quote;
import com.faith.timefloating.myutils.Constants;
import com.faith.timefloating.myutils.MyFlingButton;
import com.faith.timefloating.myutils.MyFlingImageView;
import com.faith.timefloating.utils.Common;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;
public class FirstActivity extends Activity{
private OnMyButtonEvents events;
private MyFlingButton settings;
//private int[] fromLocations = new int[2];
private ImageView dumAnchor;
private MyFlingImageView anchor;
private TranslateAnimation openTrans;
private AlphaAnimation openAlphaAnim,closeAlphaAnim;
private boolean isAnimation=false;
private Tracker mTracker;
private DataBaseHelper dbHelper;
private Quote quo;
private TextView quote;
private TextView author;
private Handler handler;
private Runnable alphaRunnable =new Runnable() {
	
	@Override
	public void run() {
		AlphaAnimation alp=new AlphaAnimation(0f, 1f);
		alp.setFillAfter(true);
		alp.setDuration(2500);
		author.startAnimation(alp);
		handler.postDelayed(refreshQuoteRunnable, 17000);
	}
};

private Runnable refreshQuoteRunnable =new Runnable() {
	
	@Override
	public void run() {
		displayQuote();
	}
};
private GifMovieView gif1;
private int currentIdx=0;
private TextView chat;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.first_layout);
		if(getIntent()!=null && getIntent().getAction()!=null && getIntent().getAction().equals("notification")){
			Intent visibleTheTime = new Intent(this,TimeFloatingService.class);
			visibleTheTime.setAction(Constants.VISIBLE_THETIME_ACTION);
			startService(visibleTheTime);
		}
		initGATracker();
		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		int height = displaymetrics.heightPixels;
		int width = displaymetrics.widthPixels;
		MyApplication.getSharedPreferences().edit().putInt(Constants.CENTER_X_POS, width/2).commit();
		MyApplication.getSharedPreferences().edit().putInt(Constants.CENTER_Y_POS, height/2).commit();
		mTracker.sendView("First Screen "+Common.getVersionCode(this));
		settings=(MyFlingButton)findViewById(R.id.openSettings);
		anchor=(MyFlingImageView)findViewById(R.id.anchor);
		dumAnchor=(ImageView)findViewById(R.id.dum_anchor);
//		DisplayMetrics dm = new DisplayMetrics();
//	    this.getWindowManager().getDefaultDisplay().getMetrics( dm );
//	    widthScreen = dm.widthPixels;
		openAlphaAnim = new AlphaAnimation(0, 1f);
		openAlphaAnim.setDuration(2000);
		openAlphaAnim.setAnimationListener(new AnimationListener() {
			
			@Override
			public void onAnimationStart(Animation animation) {
			}
			
			@Override
			public void onAnimationRepeat(Animation animation) {
				
			}
			
			@Override
			public void onAnimationEnd(Animation animation) {
			}
		});
		closeAlphaAnim = new AlphaAnimation(1f, 0f);
		closeAlphaAnim.setDuration(500);
		closeAlphaAnim.setAnimationListener(new AnimationListener() {
			@Override
			public void onAnimationStart(Animation animation) {
				
			}
			@Override
			public void onAnimationRepeat(Animation animation) {
				
			}
			@Override
			public void onAnimationEnd(Animation animation) {
				settings.setVisibility(View.INVISIBLE);
			}
		});
		dumAnchor.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				closeSettings(false);
				
			}
		});
		anchor.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
//				dumAnchor.getLocationOnScreen(locations);
//				anchor.getLocationOnScreen(fromLocations);
				openTrans = new TranslateAnimation(0,-(settings.getWidth()), 0,0);
				openTrans.setDuration(500);
		        openTrans.setAnimationListener(new AnimationListener() {
					
					@Override
					public void onAnimationStart(Animation animation) {
						isAnimation = true;
						settings.setVisibility(View.VISIBLE);
						settings.startAnimation(openAlphaAnim);
					}
					@Override
					public void onAnimationRepeat(Animation animation) {
						// TODO Auto-generated method stub
					}
					@Override
					public void onAnimationEnd(Animation animation) {
						isAnimation = false;
						dumAnchor.setVisibility(View.VISIBLE);
						anchor.setVisibility(View.INVISIBLE);
					}
				});
		        anchor.startAnimation(openTrans);
			}
		});
		events = new OnMyButtonEvents() {
			
			@Override
			public void onMyButtonFling(float velocityX, float velocityY) {
				Log.e("","");
				if(velocityX>0){
					if(settings.isExpand()){
						//collapse
						settings.changeState();
					}
				}else{
					if(!settings.isExpand()){
						//expand
						settings.changeState();
					}
				}
				
			}
		};
		settings.setOnMyButtonEvents(events);
		settings.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(!isAnimation){
					closeSettings(true);
					Toast.makeText(FirstActivity.this, getResources().getString(R.string.opening_setting), Toast.LENGTH_SHORT).show();
				}
			}
		});
		dbHelper=new DataBaseHelper(this);
		startTime();
		handler = new Handler();
		handler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				try {
					dbHelper.createDataBase();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}, 500);
		quote=(TextView)findViewById(R.id.quote);
		author=(TextView)findViewById(R.id.author);
		displayQuote();
		quote.setOnLongClickListener(new OnLongClickListener() {
			
			@Override
			public boolean onLongClick(View v) {
				if(quo!=null){
					ClipboardManager clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);;
					clipboard.setText(quo.getQuote()+" - "+quo.getAuthor());
					Toast.makeText(FirstActivity.this,getResources().getString(R.string.copied_quote), Toast.LENGTH_LONG).show();
				}
				return false;
			}
		});
		gif1 = (GifMovieView) findViewById(R.id.gif1);
		gif1.setMovieResource(R.drawable.frog_anim);
		
		chat=(TextView)findViewById(R.id.chat);
		chat.setText("Hello there");
		handler.postDelayed(autoChat, 3000);
		Intent startService = new Intent(this, TimeFloatingService.class);
		startService.setAction(Constants.UPDATE_MSGs);
		startService(startService);
		
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.opengp:
		{
			openGooglePlay();
			return true;
		}
		default :
			return super.onOptionsItemSelected(item);
		
		}
	}
//	TranslateAnimation moveToLeft=new TranslateAnimation(0, Common., fromYDelta, toYDelta)
	
	public void onGifClick(View v) {
		mTracker.sendEvent("Button Click "+Common.getVersionCode(this), "Click the frog!", "Click the frog ver "+Common.getVersionCode(this), Long.valueOf(1));
		if(isTouched){
			return;
		}
		isTouched = true;
		//do new anim
		gif1.setMovieResource(R.drawable.touched_frog_anim);
		chat.setText(getResources().getString(R.string.touched));
		handler.postDelayed(restoreState, 9000);
//		GifMovieView gif = (GifMovieView) v;
//		gif.setPaused(!gif.isPaused());
		
	}
	
	private void openGooglePlay(){
		Uri uri = Uri.parse("market://details?id=" + getPackageName());
		Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
		try {
		  startActivity(goToMarket);
		} catch (ActivityNotFoundException e) {
		  startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())));
		}
	}
	
	private volatile boolean isTouched=false;
	
	private void displayQuote() {
		author.setVisibility(View.INVISIBLE);
		quo=getRandomQuote();
		if(quo!=null){
			quote.setText(quo.getQuote());
			author.setText("- "+quo.getAuthor()+" -");
			handler.postDelayed(alphaRunnable , 5000);
		}else{
			if(!FirstActivity.this.isFinishing()){
				handler.postDelayed(new Runnable() {
					
					@Override
					public void run() {
						displayQuote();
					}
				}, 1000);
			}
		}
	}
	private Runnable restoreState = new Runnable() {
		@Override
		public void run() {
			isTouched = false;
			gif1.setMovieResource(R.drawable.frog_anim);
			chat.setText(getText());
		}
	};
	
	private Runnable autoChat = new Runnable() {
		@Override
		public void run() {
			if(isTouched){
				//touching state, do nothing!
			}else{
				chat.setText(getText());
			}
			handler.postDelayed(this, 5000);
		}
	};
	
	private Quote getRandomQuote() {
		Quote q=dbHelper.getQuote();
		if(q!=null){
//			Log.e("got quote","get quote:"+q.getQuote()+" - "+q.getAuthor());
		}else{
			Log.e("got quote","get quote null");
		}
		return q;
	}
	
	private String getText(){
		String txt ="";
		if(MyApplication.chatContents!=null && MyApplication.chatContents.size()>0){
			txt= MyApplication.chatContents.get(currentIdx);
			if(currentIdx==MyApplication.chatContents.size()-1){
				currentIdx=0;
			}else{
				currentIdx+=1;
			}
		}
		return txt;
	}
	
	@Override
		protected void onDestroy() {
		try{
			handler.removeCallbacks(refreshQuoteRunnable);
			handler.removeCallbacks(alphaRunnable);
			handler.removeCallbacks(restoreState);
			handler.removeCallbacks(autoChat);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		    SharedPreferences shared= getSharedPreferences(Constants.SHARED_NAME, MODE_PRIVATE);
		    boolean visibility=shared.getBoolean(Common.SHARED_VISIBILITY, false);
		    if(visibility){
		    	try{
					mTracker.sendView("Here I Am! "+Common.getVersionCode(this));
				}catch(IllegalStateException ex){
					if(ex.getMessage().contains("Tracker closed")){
						Log.e("GA","Handled IllegalStateExcetion!");
						initGATracker();
						mTracker.sendView("Here I Am! "+Common.getVersionCode(this));
					}
				}
				catch(Exception ex){
					ex.printStackTrace();
				}
		    }else{
		    	mTracker.close();
		    }
			super.onDestroy();
		}
	
	@Override
		protected void onPause() {
			paused=true;
			super.onPause();
		}
	private boolean paused=false;
	@Override
		protected void onResume() {
			super.onResume();
			if(paused){
				sendGAView();
			}
		}
	private void sendGAView() {
		try{
			mTracker.sendView("First Screen "+Common.getVersionCode(this));
		}catch(IllegalStateException ex){
			if(ex.getMessage().contains("Tracker closed")){
				Log.e("GA","Handled IllegalStateExcetion!");
				initGATracker();
				mTracker.sendView("First Screen "+Common.getVersionCode(this));
			}
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
	}
	private void startTime() {
		Intent startIntent = new Intent(this, TimeFloatingService.class);
		startService(startIntent);
	}
	private void closeSettings(final boolean openAsWell) {
		openTrans = new TranslateAnimation(0,settings.getWidth(), 0,0);
		openTrans.setDuration(500);
		openTrans.setAnimationListener(new AnimationListener() {
			
			@Override
			public void onAnimationStart(Animation animation) {
				isAnimation=true;
				settings.startAnimation(closeAlphaAnim);
			}
			@Override
			public void onAnimationRepeat(Animation animation) {
				// TODO Auto-generated method stub
			}
			@Override
			public void onAnimationEnd(Animation animation) {
				dumAnchor.setVisibility(View.INVISIBLE);
				anchor.setVisibility(View.VISIBLE);
				isAnimation=false;
				if(openAsWell){
					Intent intent=new Intent(FirstActivity.this, SettingsActivity.class);
					startActivity(intent);
				}
			}
		});
		dumAnchor.startAnimation(openTrans);
	}
	
	private void initGATracker() {
		GoogleAnalytics mGaInstance = GoogleAnalytics.getInstance(this);
		mTracker = mGaInstance.getTracker(getResources().getString(R.string.ga_trackingId));
	}


//    @Override
//    public boolean onDown(MotionEvent event) { 
//        Log.e(DEBUG_TAG,"onDown: " + event.toString()); 
//        return true;
//    }
//
//    @Override
//    public boolean onFling(MotionEvent event1, MotionEvent event2, 
//            float velocityX, float velocityY) {
//        Log.e(DEBUG_TAG, "onFling: " + event1.toString()+event2.toString());
//        return true;
//    }
//
//    @Override
//    public void onLongPress(MotionEvent event) {
//        Log.e(DEBUG_TAG, "onLongPress: " + event.toString()); 
//    }
//
//    @Override
//    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
//            float distanceY) {
//        Log.e(DEBUG_TAG, "onScroll: " + e1.toString()+e2.toString());
//        return true;
//    }
//
//    @Override
//    public void onShowPress(MotionEvent event) {
//        Log.e(DEBUG_TAG, "onShowPress: " + event.toString());
//    }
//
//    @Override
//    public boolean onSingleTapUp(MotionEvent event) {
//        Log.e(DEBUG_TAG, "onSingleTapUp: " + event.toString());
//        return true;
//    }
//
//    GestureDetector.OnDoubleTapListener
//    
//    @Override
//    public boolean onDoubleTap(MotionEvent event) {
//        Log.e(DEBUG_TAG, "onDoubleTap: " + event.toString());
//        return true;
//    }
//
//    @Override
//    public boolean onDoubleTapEvent(MotionEvent event) {
//        Log.e(DEBUG_TAG, "onDoubleTapEvent: " + event.toString());
//        return true;
//    }
//
//    @Override
//    public boolean onSingleTapConfirmed(MotionEvent event) {
//        Log.e(DEBUG_TAG, "onSingleTapConfirmed: " + event.toString());
//        return true;
//    }
}
